﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZM.UI.Controls;
using Baosight.ZNH.ZMCommon;


namespace Baosight.ZNH.ZM.UI
{
    /// <summary>
    /// 首页配置 
    /// /// </summary>
    /// Title:ZM91
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 高强
    /// Version: 1.0
    /// History:
    ///       2012-11-07 高强   [创建]
    ///  
    ///
    public partial class ZM91 : EFViewCmes
    {
        private const int fontSizeNumber = 14;
        private string isLeader = "否";
        public ZM91()
        {
            InitializeComponent();
            InitFontSize();
        }

        /// <summary>
        /// 初始化字体大小
        /// </summary>
        private void InitFontSize()
        {
            mainConfigRegion.FontSize = fontSizeNumber;
            produceProblemText.FontSize = fontSizeNumber + 2;
            produceProblemType.FontSize = fontSizeNumber;
            produceProblemLevel.FontSize = fontSizeNumber;
            securityRiskText.FontSize = fontSizeNumber + 2;
            riskClassify.FontSize = fontSizeNumber;
            riskLevel.FontSize = fontSizeNumber;
            ternatedeRegulationText.FontSize = fontSizeNumber + 2;
            ternatedeClassify.FontSize = fontSizeNumber;
            ternatedeSource.FontSize = fontSizeNumber;

            manageConfigRegion.FontSize = fontSizeNumber;
            resgGrid.FontSize = fontSizeNumber;
            resgGridAdd.FontSize = fontSizeNumber;
            SaveButton.FontSize = fontSizeNumber;
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
       public override void Initialize(EIInfo initData)
        {
            if (initData.GetStatus() == -1)
            {
                EFWindow.Alert("数据加载失败！");
                return;
            }
            else
            {
                EIBlock block = initData.GetBlock("result");
                produceGroup1.ColumnNumber = 4;
                produceGroup2.ColumnNumber = 4;
                securityTrapGroup1.ColumnNumber = 4;
                securityTrapGroup2.ColumnNumber = 4;
                securityDisobeyGroup1.ColumnNumber = 4;
                securityDisobeyGroup2.ColumnNumber = 4;
                bindToCheckboxGroup(block, produceGroup1, "cmes.cp.problemType");
                //bindToCheckboxGroup(block, produceGroup1, "cmes.ca.manageIndexConfig");
                bindToCheckboxGroup(block, produceGroup2, "cmes.cp.problemLevel");
                bindToCheckboxGroup(block, securityTrapGroup1, "cmes.cl.riskClassify");
                bindToCheckboxGroup(block, securityTrapGroup2, "cmes.cl.riskLevel");
                bindToCheckboxGroup(block, securityDisobeyGroup1, "cmes.cl.classify");
                bindToCheckboxGroup(block, securityDisobeyGroup2, "cmes.cl.sourceClassify");
                securityTrapGroup1.IsEnabled = false;
                securityTrapGroup2.IsEnabled = false;
                securityDisobeyGroup1.IsEnabled = false;
                securityDisobeyGroup2.IsEnabled = false;
                produceGroup1.IsEnabled = false;
                produceGroup2.IsEnabled = false;
                canShowCheckbox(initData, "resgGrid");
                canShowCheckbox(initData, "resgGridAdd");
                //EIBlock userBlock = initData.GetBlock("userInfo");
                //produceGroup1.CheckItems(userBlock.GetRows());
                //produceGroup2.CheckItems(userBlock.GetRows());
                //securityTrapGroup1.CheckItems(userBlock.GetRows());
                //securityTrapGroup2.CheckItems(userBlock.GetRows());
                //securityDisobeyGroup1.CheckItems(userBlock.GetRows());
                //securityDisobeyGroup2.CheckItems(userBlock.GetRows());

                EIBlock leaderBlock = initData.GetBlock("isLeader");
                if (leaderBlock.GetRowCount() != 0)
                {
                    IsLeader.IsChecked = leaderBlock.GetRow(0)["fdValue"].Equals("是") ? true : false;
                    isLeader = leaderBlock.GetRow(0)["fdValue"].ToString();
                }
            };
            this.resgGrid.UpdateData(initData);
            this.resgGridAdd.UpdateData(initData);
            return;
        }

       /// <summary>
       /// 判断是否配置模块被授权
       /// </summary>
       public void canShowCheckbox(EIInfo initData,string blockName)
       {
            EIBlock block = initData.GetBlock(blockName);
            EIBlock userBlock = initData.GetBlock("userInfo");
            for (int i = 0; i < block.GetRowCount(); i++)
            {
                if (block.GetRow(i)["fdModuleName"].Equals("安全隐患"))
                {
                    securityTrapGroup1.IsEnabled = true;
                    securityTrapGroup2.IsEnabled = true;
                    securityTrapGroup1.CheckItems(userBlock.GetRows());
                    securityTrapGroup2.CheckItems(userBlock.GetRows());
                }
                else if (block.GetRow(i)["fdModuleName"].Equals("安全三违"))
                {
                    securityDisobeyGroup1.IsEnabled = true;
                    securityDisobeyGroup2.IsEnabled = true;
                    securityDisobeyGroup1.CheckItems(userBlock.GetRows());
                    securityDisobeyGroup2.CheckItems(userBlock.GetRows());
                }
                else if (block.GetRow(i)["fdModuleName"].Equals("生产问题"))
                {
                    produceGroup1.IsEnabled = true;
                    produceGroup2.IsEnabled = true;
                    produceGroup1.CheckItems(userBlock.GetRows());
                    produceGroup2.CheckItems(userBlock.GetRows());
                }
            }
       }

       /// <summary>
       //初始化CheckBoxGroup
       /// </summary>
        public void bindToCheckboxGroup(EIBlock block, SimpleCheckBoxGroup checkBoxGroup, String strType)
        {
            if (block == null)
                return;
            IList<EIRow> dataList = new List<EIRow>();
            for (int i = 0; i < block.Rows.Count; i++)
            {
                EIRow row = block.GetRow(i);
                String strTemp = null;
                if (row["fdNo"] != null && !row["fdNo"].Equals(""))
                {
                    strTemp = row["fdNo"].ToString();
                    if (strTemp.Equals(strType))
                        dataList.Add(row);
                }
            }
            checkBoxGroup.Init(dataList, "fdDetailsName");

            return;
        }

        /// <summary>
        //添加可配置模块
        /// </summary>
        private void addResgBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in this.resgGrid.CheckedItems)
            {
                int index = resgGrid.Items.IndexOf(item);
                EIRow row = resgGrid.EIBlock.Rows[index];
                resgGrid.EIBlock.Rows.RemoveAt(index);
                int count = resgGridAdd.Items.Count;
                resgGridAdd.EIBlock.Rows.Insert(count, row);
            }
            return;
        }

        /// <summary>
        //删除可配置模块
        /// </summary>
        private void removeResgBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in this.resgGridAdd.CheckedItems)
            {
                int index = resgGridAdd.Items.IndexOf(item);
                EIRow row = resgGridAdd.EIBlock.Rows[index];
                resgGridAdd.EIBlock.Rows.RemoveAt(index);
                int count = resgGrid.Items.Count;
                resgGrid.EIBlock.Rows.Insert(count, row);
            }
            return;
        }

        /// <summary>
        //afterIndex前用来标识一条记录移动后的索引位置；
        /// </summary>
        private void upResgBtn_Click(object sender, RoutedEventArgs e)
        {
            int afterIndex = 0;
            if (resgGridAdd.CheckedItems.Count != 0 && resgGridAdd.Items.IndexOf(resgGridAdd.CheckedItems[0]) == 0)
            {
                afterIndex = 0;
            }
            else
            {
                afterIndex = -1;
            }
            List<string> listChecked = GetCheckedItems();
            int count = resgGridAdd.CheckedItems.Count;
            for (int i = 0; i < count; i++)
            {
                var item = resgGridAdd.CheckedItems[0];
                int originalIndex = resgGridAdd.Items.IndexOf(item);
                if ((originalIndex - afterIndex) > 1)
                {
                    EIRow row = this.resgGridAdd.EIBlock.Rows[originalIndex];
                    this.resgGridAdd.EIBlock.Rows.RemoveAt(originalIndex);
                    this.resgGridAdd.EIBlock.Rows.Insert(originalIndex - 1, row);
                    afterIndex = originalIndex - 1;
                }
                else
                {
                    afterIndex = originalIndex;
                }
            }

            ReCheckItems(listChecked);
            return;
        }
      
        /// <summary>
        //afterIndex前用来标识一条记录移动后的索引位置；
        /// </summary>
        private void downResgBtn_Click(object sender, RoutedEventArgs e)
        {

            int temp = this.resgGridAdd.CheckedItems.Count - 1;
            int afterIndex = 0;
            if (resgGridAdd.CheckedItems.Count != 0 &&
                resgGridAdd.Items.IndexOf(resgGridAdd.CheckedItems[temp]) == this.resgGridAdd.Items.Count - 1)
            {
                afterIndex = this.resgGridAdd.Items.Count - 1;
            }
            else
            {
                afterIndex = this.resgGridAdd.Items.Count;
            }
            List<string> listChecked = GetCheckedItems();

            for (int i = resgGridAdd.CheckedItems.Count - 1; i >= 0; i--)
            {
                var item = resgGridAdd.CheckedItems[i];
                int originalIndex = resgGridAdd.Items.IndexOf(item);
                if ((originalIndex + 1) < afterIndex)
                {
                    EIRow row = this.resgGridAdd.EIBlock.Rows[originalIndex];
                    this.resgGridAdd.EIBlock.Rows.RemoveAt(originalIndex);
                    this.resgGridAdd.EIBlock.Rows.Insert(originalIndex + 1, row);
                    afterIndex = originalIndex + 1;

                    //resgGridAdd.CheckAllRows();
                    //for (int j = 0; j < resgGridAdd.EIBlock.Rows.Count; j++)
                    //{
                    //    if (resgGridAdd.EIBlock.Rows[j] != row)
                    //        resgGridAdd.UncheckRow(j);
                    //}
                }
                else
                {
                    afterIndex = originalIndex;
                }
            }

            ReCheckItems(listChecked);
            return;
        }

        /// <summary>
        //获得选中的CheckedItem
        /// </summary>
        private List<string> GetCheckedItems()
        {
            List<string> lstChecked = new List<string>();
            foreach (var item in resgGridAdd.CheckedItems)
            {
                string keyId = GetStringValue(item.GetType().GetProperty("fdKeyId").GetValue(item, null));
                lstChecked.Add(keyId);
            }
            return lstChecked;
        }

        /// <summary>
        //重新选中的CheckedItem
        /// </summary>
        private void ReCheckItems(List<string> lstChecked)
        {
            resgGridAdd.CheckAllRows();
            for (int i = 0; i < resgGridAdd.Items.Count; i++)
            {
                string keyId = GetStringValue(resgGridAdd.Items[i].GetType().GetProperty("fdKeyId").GetValue(resgGridAdd.Items[i], null));

                if (!lstChecked.Contains(keyId))
                {
                    resgGridAdd.UncheckRow(i);
                }
            }
        }

        /// <summary>
        //转换为string
        /// </summary>
        public static string GetStringValue(object o)
        {
            if (o != null)
            {
                return o.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        //点击保存按钮
        /// </summary>
        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            Button _button = sender as Button;
            _button.IsEnabled = false;
            EIBlock block = this.resgGridAdd.EIBlock;
            base.TempButton = _button;
            if (block.GetRowCount() > 6)
            {
                base.OpenEFWindowAlert("最多只能选择6个可配置模块！", true);
                base.TempButtonOpen(true);
                return;
            }
            else if (block.GetRowCount() == 3 || block.GetRowCount() == 5)
            {
                DialogParameters param = new DialogParameters();
                param.CancelButtonContent = "重置";
                param.OkButtonContent = "确定";
                param.Content = "配置3个或者5个模块可能影响美观,是否继续?";
                param.Header = "确认框";
                param.Closed = WindowAlertClosed;
                EFWindow.Confirm(param);
            }
            else
            {
                setMeod();
            }
         
        }

        /// <summary>
        //发送数据到后台
        /// </summary>
        private void setMeod()
        {
            EIInfo info = new EIInfo();
            EIBlock block = this.resgGridAdd.EIBlock;
            info.Attributes[EIConstants.ServiceNameKey] = "ZM91";
            info.Attributes[EIConstants.MethodNameKey] = "save";
            info.AddBlock(block);


            EIBlock checkBlock = new EIBlock("checkBlockSave");
            EIColumn column = new EIColumn();
            column.SetName("fdKeyId");
            checkBlock.AddColumn(column);

            checkBlockForSave(produceGroup1, checkBlock);
            checkBlockForSave(produceGroup2, checkBlock);
            checkBlockForSave(securityTrapGroup1, checkBlock);
            checkBlockForSave(securityTrapGroup2, checkBlock);
            checkBlockForSave(securityDisobeyGroup1, checkBlock);
            checkBlockForSave(securityDisobeyGroup2, checkBlock);
            info.AddBlock(checkBlock);

            EIBlock leader = new EIBlock("isLeader");
            EIColumn columnLeader = new EIColumn();
            columnLeader.SetName("fdValue");
            EIRow LeaderRow = new EIRow();
            LeaderRow.Add("fdValue", isLeader);
            leader.AddColumn(columnLeader);
            leader.AddRow(LeaderRow);

            info.AddBlock(leader);
            this.Submit(info, saveCompleted);
        }

        private void WindowAlertClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，删除按钮生效
                return;
            }
            setMeod();
        }

        /// <summary>
        //需要保存的checkBox
        /// </summary>
        public void checkBlockForSave(SimpleCheckBoxGroup checkBoxGroup, EIBlock block)
        {
            IList<CheckBox> list = checkBoxGroup.checkedItems;
            for (int i = 0; i < list.Count; i++)
            {
                EIRow row = (list[i] as CheckBox).DataContext as EIRow;
                block.AddRow(row);
            }
            return;
        }

        /// <summary>
        //点击保存后的回调函数
        /// </summary>
        private void saveCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() == -1)
            {
                EFWindow.Alert("数据保存失败！");
                base.TempButtonOpen(true);
                return;
            }
            EFWindow.Alert("数据保存成功！");
            base.TempButtonOpen(true);
            //if (e.EIInfo.Attributes.ContainsKey("formStatus") && e.EIInfo.Attributes["formStatus"].ToString().Equals("-1"))
            //{
            //    this.resgGridAdd.Refresh();
            //    EFWindow.Alert("数据保存成功！");
            //    return;
            //}
        }

        /// <summary>
        //是否选中领导
        /// </summary>
        private void IsLeader_Click(object sender, RoutedEventArgs e)
        {
            if (IsLeader.IsChecked == false)
            {
                isLeader = "否";
            }
            else
            {
                isLeader = "是";
            }
        }
    }
}
